package cc.realxyq.demo.util;

import lombok.experimental.UtilityClass;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author kwhan
 * @date 2022年01月07日 13:49
 */
@UtilityClass
public class ExecutorUtil {
    public static final String SIMPLE_NAME = ExecutorUtil.class.getSimpleName();
    private static final AtomicInteger THREAD_NUM = new AtomicInteger( 1 );
    private static final ExecutorService EXECUTOR = init();


    private static ExecutorService init() {
        return new ThreadPoolExecutor(
                2,
                2,
                100,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(5),
                r -> {
                    Thread thread = Executors.defaultThreadFactory().newThread(r);
                    thread.setDaemon(true);
                    thread.setName(SIMPLE_NAME + "-thread-" + THREAD_NUM.getAndIncrement());
                    return thread;
                },
                new ThreadPoolExecutor.CallerRunsPolicy());
    }


    public static ExecutorService getExecutor() {
        return EXECUTOR;
    }
}
